set#       Copyright (c) 2009 by Korenkov Vitaly <vitaly.korenkov@yandex.com>
#
#       ***************************************************************************
#       *                                                                         *
#	*   This program is free software; you can redistribute it and/or modify  *
#	*   it under the terms of the GNU General Public License as published by  *
#	*   the Free Software Foundation; version 3 of the License.               *
#	*                                                                         *
#	***************************************************************************

import sys

from PyQt4.QtCore import QByteArray
from PyQt4.QtCore import QEvent
from PyQt4.QtCore import QString
from PyQt4.QtCore import Qt
from PyQt4.QtCore import SIGNAL
from PyQt4.QtCore import SLOT
from PyQt4.QtGui import QAction
from PyQt4.QtGui import QActionGroup
from PyQt4.QtGui import QDesktopServices
from PyQt4.QtGui import QFileDialog
from PyQt4.QtGui import QHeaderView
from PyQt4.QtGui import QInputDialog
from PyQt4.QtGui import QLineEdit
from PyQt4.QtGui import QMainWindow
from PyQt4.QtGui import QMenu
from PyQt4.QtGui import QMessageBox
from PyQt4.QtGui import QStackedLayout
from PyQt4.QtGui import QStyle
from PyQt4.QtGui import QStyleFactory
from PyQt4.QtGui import QSystemTrayIcon
from PyQt4.QtGui import QWidget
from PyQt4.QtGui import qApp
from PyQt4.QtSql import QSqlDatabase
from PyQt4.QtSql import QSqlQuery
from filesroom import FilesRoom
from globals import Globals
from libraryroom import LibraryRoom			
import locale
from mediamanager import MediaManager
from networkroom import NetworkRoom
import os
from playlist import PlayList
from ui_phonik import Ui_PhonikMainWindow

'''
Phonik:
    -gui
    -handle configuration
    -tray icon
'''


class Phonik(QMainWindow, Ui_PhonikMainWindow):

    def __init__(self):

	#parent constructor
        QMainWindow.__init__(self)

	#setup ui file
        self.setupUi(self)


        #ui objects
        self.playList = PlayList(self)
        self.mediaManager = MediaManager(self)

        #set up signals
        self.signals()

        #tray icon
        self.setupTray()

        #check first run
        self.run()

        #fill style menu
        self.menuStyles ()

        self.checkArgs()


    def run(self):
        #check existence of the config dir
        if os.path.exists(Globals.phonikPath):
            self.setupDB()
            self.setupUi2()

        #first run
        else:
            #create dirs
            os.makedirs(Globals.phonikPath)

            self.setupDB()
            self.createDBTables()

            #setup the rest ui objects
            self.setupUi2()


            self.playList.setColumnWidth(0, 50)
            self.playList.setColumnWidth(2, 170)
            self.playList.setColumnWidth(3, 170)
            self.playList.setColumnWidth(4, 50)
            self.playList.setColumnWidth(5, 55)
            self.playList.horizontalHeader().setMovable(True)
            self.playList.horizontalHeader().setResizeMode(QHeaderView.Interactive)
            self.playList.horizontalHeader().setResizeMode(1, QHeaderView.Stretch)
            self.playList.setColumnHidden(4, True)
            self.playList.setColumnHidden(6, True)
            self.playList.setColumnHidden(7, True)

            #splitter widgets size
            self.splitter.setSizes([100, 100])



    def checkArgs(self, args=None):

        if not args:
            args = sys.argv

        if len(args) > 1:
            self.mediaManager.playList.clearModel()

        del args[0]
        
        for arg in args:
            self.play(arg, True, True)

    def createDBTables(self):
        self.query.exec_('create table settings (key varchar(20) unique, value varchar)')
        self.query.exec_('create table network (name varchar(20), url varchar unique)')
        self.query.exec_('create table genres (genre varchar(50) unique)')
        self.query.exec_('create table artists (artist varchar(50), genre varchar(50), unique(artist, genre))')
        self.query.exec_('create table albums (album varchar(50), artist varchar(50), genre varchar(50),unique(album,artist,genre))')
        self.query.exec_('create table titles (track varchar(3), title  varchar(100), artist varchar(50), album varchar(50), date varchar(10), time varchar(8), genre varchar(50), file varchar(400) unique)')


        #default values for the fist run
        self.setValue('room', '''<class 'filesroom.FilesRoom'>''')
        self.setValue('minimize', '0')
        self.setValue('files-view', 'columns')
        self.setValue('root', os.path.expanduser('~'))
        self.setValue('show-artist', "1")


    def setupDB(self):
        self.db = QSqlDatabase.addDatabase('QSQLITE')
        self.db.setDatabaseName(Globals.phonikPath + os.sep + 'phonik-db')

        if self.db.open():
            self.query = QSqlQuery()
        else:
            QMessageBox.warning(self, 'Phonik', self.tr('Can not find the SQLITE3 library'), QMessageBox.Ok)


    def setupUi2(self):

        #place playlist
        self.stackedWidget = QWidget()
        self.stackedLayout = QStackedLayout(self.stackedWidget)
        self.splitter.addWidget(self.stackedWidget)
        self.splitter.addWidget(self.playList)

        #buttons
        self.playButton.setIcon(self.style().standardIcon(QStyle.SP_MediaPlay))
        self.nextButton.setIcon(self.style().standardIcon(QStyle.SP_MediaSkipForward))
        self.prevButton.setIcon(self.style().standardIcon(QStyle.SP_MediaSkipBackward))
        self.shuffleButton.setIcon(self.style().standardIcon(QStyle.SP_FileDialogInfoView))
        self.repeatButton.setIcon(self.style().standardIcon(QStyle.SP_BrowserReload))

        #show the library dir in the main menu
        self.updateLibraryDirsMenu()
        self.restoreStates()

        #group rooms
        roomGroup = QActionGroup(self)
        roomGroup.addAction(self.actionSelectFilesRoom)
        roomGroup.addAction(self.actionSelectLibraryRoom)
        roomGroup.addAction(self.actionSelectNetworkRoom)

        #group files places
        filesGroup = QActionGroup(self)
        filesGroup.addAction(self.actionShowColumns)
        filesGroup.addAction(self.actionShowIcons)
        filesGroup.addAction(self.actionShowTable)
        

    def menuStyles(self):

        group = QActionGroup(self)
        for style in QStyleFactory.keys():
            action = QAction (style, self)
            action.setCheckable (True)

            if style.toLower () == qApp.style ().objectName ():
                action.setChecked (True)

            action.setProperty ("style", style)
            self.connect(action, SIGNAL('triggered ()'), self.changeStyle)
            group.addAction(action)
            self.menuStyle.addAction (action)


    def changeStyle (self, style=0):
        if style:
            qApp.setStyle (style)
        else:
            qApp.setStyle (self.sender ().property ("style").toString ())

    def hideRooms(self, checked):
        self.splitter.widget(0).setHidden(checked)


    def playFiles(self):
        fileNames = QFileDialog.getOpenFileNames(self, self.tr('Select files'), QDesktopServices.storageLocation(QDesktopServices.MusicLocation))

        if fileNames:
            urls = []
            for fileName in fileNames:
                urls.append(str(fileName.toUtf8()))

        if urls:
            self.playUrls(urls)


    def play(self, path, recursively=True, toPlaylist=False, toLibrary=False):
        if os.path.isdir(path):
            self.mediaManager.addDir(path, recursively, toPlaylist, toLibrary)
        else:
            self.playUrls([path], toPlaylist)


    def playUrls(self, urls=None, toPlaylist=False):

        if not urls:
            urls = [str(QInputDialog.getText(self, self.tr('Input a URL'), self.tr("URL:"), QLineEdit.Normal)[0])]

        if urls:
            for file in urls:
                if 'http' in file.lower():
                    self.mediaManager.addUrls([file], toPlaylist)
                elif not self.hasPlayList(urls[0]):
                    if os.path.exists(file):
                        self.mediaManager.addUrls([file], toPlaylist)
        if hasattr(self, 'libraryRoom'):
            self.libraryRoom.loadLibrary()
                        
                
    def hasPlayList(self, file):
        if file.lower().endswith('.m3u'):
            for line in open(file).readlines():
                line = line.strip()
                if not line.startswith('#') and line != '':
                    if line.startswith('http://'):
                        self.mediaManager.addUrls([line])
                    else:
                        self.mediaManager.addUrls([file[:file.rfind(os.sep) + 1] + line])
            return True
        elif file.lower().endswith('.pls'):
            for line in open(file).readlines():
                if line.strip().lower().startswith('file'):
                    self.mediaManager.addUrls([line[line.find('=') + 1:].strip()])
        return False


    def playDir(self, dir=None, recursively=True, toPlaylist=False, toLibrary=False):
        if not dir:
            dir = QFileDialog.getExistingDirectory(self, self.tr('Select a folder'), QDesktopServices.storageLocation(QDesktopServices.MusicLocation), QFileDialog.ShowDirsOnly)
            dir = str(dir.toUtf8())
        if dir:
            self.mediaManager.addDir(dir, recursively, toPlaylist, toLibrary)


    def selectFilesRoom(self, root=None):
        if not hasattr(self, 'filesRoom'):
            self.filesRoom = FilesRoom(self, self.getValue('root'), self.getValue('files-view'))
            self.stackedLayout.addWidget(self.filesRoom)
            self.connect(self.actionShowIcons, SIGNAL('triggered()'), self.filesRoom.setIconsView)
            self.connect(self.actionShowTable, SIGNAL('triggered()'), self.filesRoom.setTableView)
            self.connect(self.actionShowColumns, SIGNAL('triggered()'), self.filesRoom.setColumnsView)
            self.connect(self.actionUpdate, SIGNAL('triggered ()'), self.filesRoom.filesModel.refresh)

        self.stackedLayout.setCurrentWidget(self.filesRoom)

        #set sorting by albums
        self.playList.setSortIndicator(3)

        self.actionSelectFilesRoom.setChecked(True)
        self.actionSelectLibraryRoom.setChecked(False)
        self.actionSelectNetworkRoom.setChecked(False)

        if root:
            self.filesRoom.setRoot(root)


    def selectLibraryRoom (self):
        if not hasattr(self, 'libraryRoom'):
            self.libraryRoom = LibraryRoom(self)
            self.connect(self.actionResetLibrary, SIGNAL('triggered()'), self.libraryRoom.loadLibrary)
            
            if not self.actionShowGenres.isChecked():
                self.libraryRoom.genresView.setHidden(True)
            if not self.actionShowArtists.isChecked():
                self.libraryRoom.artistsView.setHidden(True)
            if not self.actionShowAlbums.isChecked():
                self.libraryRoom.albumsView.setHidden(True)

            self.stackedLayout.addWidget(self.libraryRoom)

        self.stackedLayout.setCurrentWidget(self.libraryRoom)
        self.actionSelectFilesRoom.setChecked(False)
        self.actionSelectLibraryRoom.setChecked(True)
        self.actionSelectNetworkRoom.setChecked(False)

    def selectNetworkRoom(self):
        if not hasattr(self, 'networkRoom'):
            self.networkRoom = NetworkRoom(self)
            self.stackedLayout.addWidget(self.networkRoom)

        self.stackedLayout.setCurrentWidget(self.networkRoom)

        self.actionSelectFilesRoom.setChecked(False)
        self.actionSelectLibraryRoom.setChecked(False)
        self.actionSelectNetworkRoom.setChecked(True)

        self.networkRoom.update()

    def addLibraryDir(self):

        #select dir
        dir = QFileDialog.getExistingDirectory(self, self.tr('Select a folder'), QDesktopServices.storageLocation(QDesktopServices.MusicLocation), QFileDialog.ShowDirsOnly)
        dir = str(dir.toUtf8())

        libraryDirs = self.getValue('library-dirs')

        if dir not in libraryDirs:

            #show library
            self.actionSelectLibraryRoom.trigger()

            #scan dir
            self.playDir(dir, True, False, True)

            #save path
            self.setValue('library-dirs', libraryDirs + '//|\\' + dir)

            #update menu
            self.updateLibraryDirsMenu()

            #load library


    def removeLibraryDir(self):
        action = self.sender()

        #remove library dir from config
        self.setValue('library-dirs', self.getValue('library-dirs').replace('//|\\' + str(action.text().toUtf8()), ''))
        self.libraryRoom.cleanLibrary()
        self.updateLibraryDirsMenu()
        if hasattr(self, 'libraryRoom'):
            self.libraryRoom.loadLibrary()


    def updateLibraryDirsMenu(self):

        self.menuLibraryDirs.clear()

        for dir in self.getValue('library-dirs').split('//|\\'):
            if not dir.isEmpty():
                action = QAction(QString.fromUtf8(dir), self)
                self.menuLibraryDirs.addAction(action)
                self.connect(action, SIGNAL('triggered()'), self.removeLibraryDir)


    def rescan(self):

        for dir in self.getValue('library-dirs').split('//|\\'):
            if not dir.isEmpty():
                #scan dir
                self.libraryRoom.cleanLibrary()
                self.playDir(dir, True, False, True)

    def setLibraryViews(self, action):
        if hasattr(self, 'libraryRoom'):
            if action is self.actionShowGenres:
                self.libraryRoom.genresView.setHidden(not self.libraryRoom.genresView.isHidden())
            elif action is self.actionShowArtists:
                self.libraryRoom.artistsView.setHidden(not self.libraryRoom.artistsView.isHidden())
            elif action is self.actionShowAlbums:
                self.libraryRoom.albumsView.setHidden(not self.libraryRoom.albumsView.isHidden())
            self.libraryRoom.loadLibrary()


    def addNetworkStation(self):

        name = QInputDialog.getText(self, self.tr('The station name'), self.tr('Enter the station name'), QLineEdit.Normal, 'Station1')
        if name[1]:
            result = QInputDialog.getText(self, self.tr('The URL'), self.tr('Enter the URL'), QLineEdit.Normal, 'http://')
            if result[1]:
                self.query.exec_('insert into network values("' + name[0] + '","' + result[0] + '")')
                if hasattr(self, 'networkRoom'):
                    self.networkRoom.update()


    def setMusicDir(self):
        dir = QFileDialog.getExistingDirectory(self, self.tr('Select the music folder'), QDesktopServices.storageLocation(QDesktopServices.MusicLocation), QFileDialog.ShowDirsOnly)
        if dir:
            self.selectFilesRoom(dir)
            self.setValue('root', dir)
        

    def setupTray(self):
        trayMenu = QMenu(self)

        trayMenu.addAction(self.actionShowNowPlaying)
        trayMenu.addSeparator()
        
        trayMenu.addAction(self.actionNext)
        trayMenu.addAction(self.actionPrev)

        trayMenu.addSeparator()
        trayMenu.addAction(self.actionExit)

        self.systemTrayIcon = QSystemTrayIcon()
        self.systemTrayIcon.setContextMenu(trayMenu)
        self.systemTrayIcon.setIcon(self.style().standardIcon(QStyle.SP_MediaStop))
        self.systemTrayIcon.show()
        self.systemTrayIcon.installEventFilter(self)

        self.connect(self.systemTrayIcon, SIGNAL('activated(QSystemTrayIcon::ActivationReason)'), self.trayClicked)


    def trayClicked(self, reason):
        if reason == QSystemTrayIcon.Trigger:
            pass
            #if self.isActiveWindow():
            #    self.setHidden(not self.isHidden())
            #if self.isMinimized():
            #    self.activateWindow()
            #    self.raise_()
            #else:
            if self.isHidden():
                self.setHidden(False)
            else:
                if self.isActiveWindow():
                    self.setHidden(True)
                else:
                    self.activateWindow()
                    self.raise_()


            #self.setHidden(not self.isHidden())
            
        elif reason == QSystemTrayIcon.MiddleClick:
            self.mediaManager.playPause()


    def activate(self):
        self.activateWindow()
        self.raise_()
        if self.isHidden():
            self.show()
        if self.isMinimized():
            self.showNormal()


    def eventFilter(self, object, event):
        if object is self.systemTrayIcon and event.type() == QEvent.Wheel:
            delta = event.delta()
            audioOutput = self.mediaManager.audioOutput

            #if the middle mouse button is held
            if qApp.mouseButtons() == Qt.MidButton:
                if delta > 0:
                    self.mediaManager.prev()
                else:
                    self.mediaManager.next()
            else:
                if delta > 0:
                    #increase volume
                    if self.mediaManager.audioOutput.volume() <= 0.9:
                        audioOutput.setVolume(audioOutput.volume() + 0.1)
                    else:
                        audioOutput.setVolume(1)
                else:
                    #decrease volume
                    if audioOutput.volume() > 0.1:
                        audioOutput.setVolume(audioOutput.volume() - 0.1)
                    else:
                        audioOutput.setVolume(0)
                self.systemTrayIcon.showMessage(self.tr('Volume'), str(int(audioOutput.volume() * 100)) + '%', QSystemTrayIcon.NoIcon, 700)

            event.accept()
            return True
        
        return False


    def signals(self):

        self.actionNext = QAction(self.tr('Next'), self)
        self.actionNext.setIcon(self.style().standardIcon(QStyle.SP_MediaSkipForward))
        self.connect(self.actionNext, SIGNAL('triggered()'), self.mediaManager.next)

        self.actionPrev = QAction(self.tr('Prev'), self)
        self.actionPrev.setIcon(self.style().standardIcon(QStyle.SP_MediaSkipBackward))
        self.connect(self.actionPrev, SIGNAL('triggered()'), self.mediaManager.prev)

        self.connect(self.actionExit, SIGNAL('triggered()'), qApp, SLOT('quit()'))
        self.connect(self.actionSelectFilesRoom, SIGNAL('triggered()'), self.selectFilesRoom)
        self.connect(self.actionSelectLibraryRoom, SIGNAL('triggered()'), self.selectLibraryRoom)
        self.connect(self.actionSelectNetworkRoom, SIGNAL('triggered()'), self.selectNetworkRoom)
        self.connect(self.actionHideRooms, SIGNAL('triggered(bool)'), self.hideRooms)
        self.connect(self.actionPlayFiles, SIGNAL('triggered()'), self.playFiles)
        self.connect(self.actionPlayDir, SIGNAL('triggered()'), self.playDir)
        self.connect(self.actionPlayUrl, SIGNAL('triggered()'), self.playUrls)
        self.connect(self.actionAddLibraryDir, SIGNAL('triggered()'), self.addLibraryDir)
        self.connect(self.actionRescanLibrary, SIGNAL('triggered()'), self.rescan)
        self.connect(self.actionAddStation, SIGNAL('triggered()'), self.addNetworkStation)
        self.connect(self.nextButton, SIGNAL('pressed()'), self.mediaManager.next)
        self.connect(self.prevButton, SIGNAL('pressed()'), self.mediaManager.prev)
        self.connect(self.shuffleButton, SIGNAL('pressed()'), self.mediaManager.shuffle)        
        self.connect(self.actionSetMusicDir, SIGNAL('triggered()'), self.setMusicDir)
        self.connect(qApp, SIGNAL('aboutToQuit()'), self.saveStates)
        self.connect(self.menuLibrary, SIGNAL('triggered(QAction *)'), self.setLibraryViews)
        self.connect(self.titleLabel, SIGNAL('linkActivated ( const QString & )'), self.selectLibraryRecord)
        self.connect(self.actionShowArtistName, SIGNAL('triggered ()'), self.mediaManager.metaDataChanged)
        self.connect(self.actionShowAlbumName, SIGNAL('triggered ()'), self.mediaManager.metaDataChanged)


    def selectLibraryRecord(self, link):
        if hasattr(self, 'libraryRoom'):
            if 'artist' in link:
                self.libraryRoom.selectArtist(link.split(':')[1])
            elif 'album' in link:
                self.libraryRoom.selectAlbum(link.split(':')[1])
            elif 'title' in link:
                self.libraryRoom.selectFullPath(link.split(':')[1])
        


    def closeEvent(self, event):

        if self.actionMinimizeOnClose.isChecked():
            self.hide()
            event.ignore()
        else:
            event.accept()


    def restoreStates(self):

        #repeat button state
        if self.getValue('repeat') == '1':
            self.repeatButton.setChecked(True)

        #minimize action state
        if self.getValue('minimize') == '1':
            self.actionMinimizeOnClose.setChecked(True)

        if self.getValue('save-playlist') == '1':
            self.playList.restore()

        #save playlist state
        if self.getValue('save-playlist') == '1':
            self.actionSavePlaylistOnClose.setChecked(True)

        #show now playing
        if self.getValue('now-playing') == '1':
            self.actionShowNowPlaying.setChecked(True)

        #rooms
        if self.getValue('show-genres') == '0':
            self.actionShowGenres.setChecked(False)
        if self.getValue('show-artists') == '0':
            self.actionShowArtists.setChecked(False)
        if self.getValue('show-albums') == '0':
            self.actionShowAlbums.setChecked(False)

        #show artist and album
        if self.getValue('show-artist') == '0':
            self.actionShowArtistName.setChecked(False)

        if self.getValue('show-album') == '1':
            self.actionShowAlbumName.setChecked(True)


        #select room
        if self.getValue('room') == '''<class 'filesroom.FilesRoom'>''':
            self.actionSelectFilesRoom.trigger()
        elif self.getValue('room') == '''<class 'libraryroom.LibraryRoom'>''':
            self.actionSelectLibraryRoom.trigger()
        elif self.getValue('room') == '''<class 'networkroom.NetworkRoom'>''':
            self.actionSelectNetworkRoom.trigger()

        #rooms frame
        if self.getValue('rooms-hidden') == '1':
            self.actionHideRooms.setChecked(True)
            self.stackedWidget.setHidden(True)

        #restore style
        style = self.getValue('style')
        if style:
            qApp.setStyle (style)

        #restore states
        self.restoreGeometry(QByteArray.fromBase64(self.getValue('geometry').toAscii()))
        self.restoreState(QByteArray.fromBase64(self.getValue('state').toAscii()))
        self.playList.horizontalHeader().restoreState(QByteArray.fromBase64(self.getValue('playlist-header').toAscii()))
        self.splitter.restoreState(QByteArray.fromBase64(self.getValue('splitter').toAscii()))

        
    def saveStates(self):

        #repeat button state
        if self.repeatButton.isChecked():
            self.setValue('repeat', '1')

        #minimize action state
        if self.actionMinimizeOnClose.isChecked():
            self.setValue('minimize', '1')
        else:
            self.setValue('minimize', '0')

        if self.actionSavePlaylistOnClose.isChecked():
            self.playList.save()

        #save playlist state
        if self.actionSavePlaylistOnClose.isChecked():
            self.setValue('save-playlist', '1')
        else:
            self.setValue('save-playlist', '0')

        #show now playing
        if self.actionShowNowPlaying.isChecked():
            self.setValue('now-playing', '1')
        else:
            self.setValue('now-playing', '0')

        #save files view
        if self.actionShowIcons.isChecked():
            self.setValue('files-view', 'icons')
        elif self.actionShowTable.isChecked():
            self.setValue('files-view', 'table')
        elif self.actionShowColumns.isChecked():
            self.setValue('files-view', 'columns')

        #library view actions
        if self.actionShowGenres.isChecked():
            self.setValue('show-genres', '1')
        else:
            self.setValue('show-genres', '0')
        if self.actionShowArtists.isChecked():
            self.setValue('show-artists', '1')
        else:
            self.setValue('show-artists', '0')
        if self.actionShowAlbums.isChecked():
            self.setValue('show-albums', '1')
        else:
            self.setValue('show-albums', '0')

        #rooms
        if self.actionHideRooms.isChecked():
            self.setValue('rooms-hidden', '1')
        else:
            self.setValue('rooms-hidden', '0')

        #show artist and album
        if self.actionShowArtistName.isChecked():
            self.setValue('show-artist', '1')
        else:
            self.setValue('show-artist', '0')
        
        if self.actionShowAlbumName.isChecked():
            self.setValue('show-album', '1')
        else:
            self.setValue('show-album', '0')

        #save style
        self.setValue('style', qApp.style ().objectName ())

        #save states
	self.setValue('state', self.saveState().toBase64().data())
	self.setValue('geometry', self.saveGeometry().toBase64().data())
        self.setValue('splitter', self.splitter.saveState().toBase64().data())
        self.setValue('playlist-header', self.playList.horizontalHeader().saveState().toBase64().data())
        self.setValue('room', str(self.stackedLayout.currentWidget().__class__))

        self.query.exec_('vacuum')


    def setValue(self, key, value):
        self.query.exec_('replace into settings values("' + key + '","' + value + '")')


    def getValue(self, key):
        self.query.exec_('select value from settings where key="' + key + '"')
        if self.query.next():
            return self.query.value(0).toString()
        else:
            return QString()


if __name__ == '__main__':


    #os.system('rm -r ~/.config/phonik.py')
    print '--compile gui--'
    os.system('pyuic4 -o ui_phonik.py ../ui/phonik.ui')

    #russian translation
    print '--update translation--'
    os.system('pylupdate4 *.py -ts ../translations/phonik.ru_ru.ts')
    os.system('pylupdate4 *.py -ts ../translations/phonik.cs_cz.ts')
    os.system('lrelease ../translations/phonik.ru_ru.ts -qm ../translations/phonik.ru_ru.qm')
    os.system('lrelease ../translations/phonik.cs_cz.ts -qm ../translations/phonik.cs_cz.qm')

    from PyQt4.QtGui import QApplication
    app = QApplication(sys.argv)
    app.setApplicationName("Phonik")

    from PyQt4.QtCore import QTranslator
    translator = QTranslator()
    translator.load('../translations/phonik.' + locale.getdefaultlocale()[0].lower() + '.qm')
    app.installTranslator(translator)

    from phonik import Phonik
    phonik = Phonik()
    phonik.show()
    sys.exit(app.exec_())
